'use strict';

import { app, protocol, BrowserWindow, Menu, ipcMain, dialog, session } from 'electron';
import ipcMethods from "@/utils/ipcMethods";
import startNodeService from "@/utils/nodeService";
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib';

const fs = require("fs");
const path = require("path");
const sd = require("silly-datetime");
const isDevelopment = process.env.NODE_ENV !== 'production';

if (process.env.NODE_ENV !== 'development') {
  app.setPath('documents', path.resolve(process.resourcesPath, '../', 'documents'));
}

app.commandLine.appendSwitch('force_high_performance_gpu'); // 有独显时启动独显渲染

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
]);

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    show: false,
    width: 962,
    height: 572,
    minWidth: 962,
    minHeight: 572,
    icon: `${__static}/icon.ico`,
    webPreferences: {
      webSecurity: false, // 允许跨域
      backgroundColor: '#FFFFFF',
      nodeIntegration: true, // 渲染层可以使用node
      contextIsolation: false
    }
  });
  win.maximize();
  win.show();

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol('app');
    // Load the index.html when not in development
    win.loadURL('app://./index.html');
    // win.webContents.openDevTools();
  }

  createMenu();
  getReSize(win);

  const filter = {
    urls: ['app://cesium/Cesium/ThirdParty/Workers/basis_transcoder.js']
  };
  session.defaultSession.webRequest.onBeforeRequest(filter, (details, callback) => {
    callback({
      redirectURL:
        "app://./cesium/Cesium/ThirdParty/Workers/basis_transcoder.js",
    });
  });
  startNodeService();
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  // if (isDevelopment && !process.env.IS_TEST) {
  //   // Install Vue Devtools
  //   try {
  //     await installExtension(VUEJS_DEVTOOLS)
  //   } catch (e) {
  //     console.error('Vue Devtools failed to install:', e.toString())
  //   }
  // }
  createWindow();
});

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit();
      }
    });
  } else {
    process.on('SIGTERM', () => {
      app.quit();
    });
  }
}

// 设置菜单栏
function createMenu() {
  // darwin表示macOS，针对macOS的设置
  if (process.platform === 'darwin') {
    const template = [{
      label: 'Electron',
      submenu: [{
        role: 'about'
      }, {
        role: 'quit'
      }]
    }];
    const menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    // windows及linux系统
    Menu.setApplicationMenu(null);
  }
}

// 监听窗口缩放
function getReSize(win) {
  if (win) {
    win.on('resize', () => {
      const size = win.getSize();
      win.webContents.send('resizeEvent', JSON.stringify(size));
    });
  }
}

// 打开文件夹
ipcMain.on("show-open-dialog", (event, data = {}) => {
  const option = {
    title: data.title || "选择要上传的文件",
    filters: data.filters || [{name: "file", extensions: ["json"]}],
    buttonLabel: data.buttonLabel || "打开",
  };
  dialog.showOpenDialog(option).then((res) => {
    const filePath = res.filePaths[0];
    let fileSize = null;
    let fileContent = null;
    if (filePath) {
      const stat = fs.statSync(filePath);
      fileSize = stat.size / 1024 / 1024;
      if (fileSize <= 10) {
        const readFileSync = fs.readFileSync(filePath, "utf-8");
        fileContent = readFileSync.toString();
      }
    }
    event.sender.send("show-open-dialog", {
      filePath,
      fileSize,
      fileContent,
    });
  });
});

// 保存文件夹
ipcMain.on("show-save-dialog", (event, data) => {
  const {fileContent} = data;
  const options = {
    title: "保存文件",
    defaultPath: `C:\\新建文件_${sd.format(
        new Date(),
        "YYYY-MM-DD-HH-mm-ss"
    )}.json`,
    filters: [{name: "JSON", extensions: ["json"]}],
  };
  dialog
      .showSaveDialog(options)
      .then((result) => {
        const {canceled, filePath} = result;
        if (!canceled && filePath) {
          fs.writeFileSync(result.filePath, fileContent);
          const stat = fs.statSync(filePath);
          const fileSize = stat.size / 1024 / 1024;
          event.sender.send("show-save-dialog", {
            filePath,
            fileSize,
            fileContent,
          });
        }
      })
      .catch((err) => {
        console.log(err);
      });
});

// 退出
ipcMain.on("app-exit", (event, data) => {
  app.exit();
});

// 处理文件上传并保存到本地目录
ipcMain.on("upload-file", (event, data) => {
  const {filePath, fileName} = data;
  let saveDir = "";
  if (process.env.NODE_ENV !== "development") {
    saveDir = process.resourcesPath;
  } else {
    saveDir = "E:\\work\\HTHT\\open-viewer\\static\\documents"; // 选择保存目录
  }
  const savePath = path.join(saveDir, fileName);
  // 确保保存目录存在
  if (!fs.existsSync(saveDir)) {
    fs.mkdirSync(saveDir);
  }

  // 读取文件内容并保存到指定目录
  fs.readFile(filePath, (err, data) => {
    if (err) {
      console.error("Error reading file:", err);
      return;
    }

    fs.writeFile(savePath, data, (err) => {
      if (err) {
        console.error("Error saving file:", err);
        return;
      }

      console.log(`File saved successfully to ${savePath}`);
      event.reply("file-saved", savePath); // 回复渲染进程，文件保存成功
    });
  });
});
